﻿using MB.RuleBase.Common;
using Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Business
{
    public class BGoods
    {
        /// <summary>
        /// 获取GOODSID
        /// </summary>
        /// <param name="goodsCode"></param>
        /// <param name="weight"></param>
        /// <returns></returns>
        public int GetGoodsID(string goodsCode)
        {
            try
            {
                return DatabaseExcuteByXmlHelper.NewInstance.ExecuteScalar<int>("Goods", "GetGoodsID", goodsCode);


            }
            catch (Exception ex)
            {
                MB.Util.TraceEx.Write(ex.Message);
                return 0;
            }
        }


        public List<Goods> getAllGoods()
        {
            try
            {
                List<Goods> lst=new List<Goods> ();
                lst = DatabaseExcuteByXmlHelper.NewInstance.GetObjectsByXml<Goods>("Goods", "GetAllGoodsInfo");
                return lst;
            }
            catch (Exception ex)
            {
                MB.Util.TraceEx.Write(ex.Message);
                return null;
            }
        }

        public GoodsInfo GetGoodsInfoByBarCode(string barCode)
        {
            try
            {
                GoodsInfo _goods = DatabaseExcuteByXmlHelper.NewInstance.GetObjectsByXml<GoodsInfo>("Goods", "GetGoodsByBarCode", new object[] { barCode }).FirstOrDefault();

                if (_goods != null)
                    return _goods;
                else
                    return null;
            }
            catch (Exception ex)
            {
                MB.Util.TraceEx.Write(ex.Message);
                return null;
            }
        }

        //补货打印数据
        public List<GoodsInfo> GetOutWarningGoodsInfo()
        {
            try
            {
                List<GoodsInfo> _goods = DatabaseExcuteByXmlHelper.NewInstance.GetObjectsByXml<GoodsInfo>("Goodsinventory", "GetOutWarningGoodsStock");

                if (_goods != null)
                    return _goods;
                else
                    return null;
            }
            catch (Exception ex)
            {
                MB.Util.TraceEx.Write(ex.Message);
                return null;
            }
        }

        public List<PrintBatchModel> GetPftPrintBatchInfo(DateTime RationDate, int BatchNO)
        {
            try
            {
                List<PrintBatchModel> _goods = DatabaseExcuteByXmlHelper.NewInstance.GetObjectsByXml<PrintBatchModel>("Goodsinventory", "GetPftPrintBatchInfo", RationDate, BatchNO);

                if (_goods != null)
                    return _goods;
                else
                    return null;
            }
            catch (Exception ex)
            {
                MB.Util.TraceEx.Write(ex.Message);
                return null;
            }
        }

        //[Obsolete("This property is duplicated with XXX", true)]定义方法过期
        public List<PrintOffShelvesModel> GetOffShelvesPrintInfo(DateTime RationDate, int BatchNO)
        {
            try
            {
                List<PrintOffShelvesModel> _goods = DatabaseExcuteByXmlHelper.NewInstance.GetObjectsByXml<PrintOffShelvesModel>("Goodsinventory", "GetOffShelvesPrintInfo", RationDate, BatchNO);

                if (_goods != null)
                    return _goods;
                else
                    return null;
            }
            catch (Exception ex)
            {
                MB.Util.TraceEx.Write(ex.Message);
                return null;
            }
        }

        public bool  UpdatePFTInventoryPrintDate(int GoodsID)
        {
            try
            {
                return DatabaseExcuteByXmlHelper.NewInstance.ExecuteNonQuery("Goodsinventory", "UpdatePftInventoryPrintDate",GoodsID) > 0;
            }
            catch (Exception ex)
            {
                MB.Util.TraceEx.Write(ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 获取货位商品信息
        /// </summary>
        /// <param name="locationcode"></param>
        /// <returns></returns>
        public List<PFTGOODSinventoryModel.GetGoodsModel> Getgoods(string locationcode)
        {
            try
            {
                List<PFTGOODSinventoryModel.GetGoodsModel> list = new List<PFTGOODSinventoryModel.GetGoodsModel>();
                list = DatabaseExcuteByXmlHelper.NewInstance.GetObjectsByXml<PFTGOODSinventoryModel.GetGoodsModel>("Goods", "GetGoodsinventory", locationcode);
                return list;
            }
            catch (Exception ex)
            {
                MB.Util.TraceEx.Write(ex.Message);
                return null;
            }
        
        }

        public pft_middle_inventoryTMP GetMiddlegoodsInventory(string GoodsCode)
        {
            try
            {
                pft_middle_inventoryTMP list = new pft_middle_inventoryTMP();
                list = DatabaseExcuteByXmlHelper.NewInstance.GetObjectsByXml<pft_middle_inventoryTMP>("Goods", "GetMiddleGoodsinventory", GoodsCode).FirstOrDefault();
                return list;
            }
            catch (Exception ex)
            {
                MB.Util.TraceEx.Write(ex.Message);
                return null;
            }

        }

        public pft_middle_inventoryTMP GetgoodsInventoryByGoodsCode(string GoodsCode)
        {
            try
            {
                pft_middle_inventoryTMP list = new pft_middle_inventoryTMP();
                list = DatabaseExcuteByXmlHelper.NewInstance.GetObjectsByXml<pft_middle_inventoryTMP>("Goods", "GetGoodsinventoryByGoodsCode", GoodsCode).FirstOrDefault();
                return list;
            }
            catch (Exception ex)
            {
                MB.Util.TraceEx.Write(ex.Message);
                return null;
            }

        }

        /// <summary>
        /// 商品报损
        /// </summary>
        /// <param name="message"></param>
        /// <param name="UpdateGoodsinventory"></param>
        /// <returns></returns>
        public bool UpdatePft_goodsinventory(out string message, List<PFTGOODSinventoryModel.GetGoodsModel> UpdateGoodsinventory, string UnShelveType)
        {
            string msg = "";
            message = null;
            bool Update = false;
            var oracle = new MB.RuleBase.BulkCopy.SimulatedOracleHelper();
            var db = MB.Orm.Persistence.DatabaseHelper.CreateDatabase();
            var cn = oracle.CreateOracleConnection(db.ConnectionString);
            System.Data.Common.DbTransaction tran = null;
            try
            {
                cn.Open();
                tran = cn.BeginTransaction();

                //List<Model.Goods.UpdateGoodsModel> _GoodsModel = new List<Goods.UpdateGoodsModel>();//库存修改
                List<PFTGOODSinventoryModel.GetGoodsModel> _GoodsModel = new List<PFTGOODSinventoryModel.GetGoodsModel>();
                List<PFTGOODSinventoryModel.PostWarehouseShelvesModel> _WarehouseShel = new List<PFTGOODSinventoryModel.PostWarehouseShelvesModel>();//在线库存
                List<PFTGOODSinventoryModel.PFT_GoodsinventoryHis> _PFT_GoodsinventoryHis = new List<PFTGOODSinventoryModel.PFT_GoodsinventoryHis>();//摘果仓上下级记录
                List<pft_middle_goodsinventoryhis> LstmiddlePFTStockHis = new List<pft_middle_goodsinventoryhis>();//中间仓上下架记录
                List<pft_middle_goodsinventory> listmiddlePFTStock =new List<pft_middle_goodsinventory> ();//中间仓上下架
                foreach (var _Goods in UpdateGoodsinventory)
                {
                    PFTGOODSinventoryModel.GetGoodsModel _UpdateGoodsModel = new PFTGOODSinventoryModel.GetGoodsModel();
                    _UpdateGoodsModel.GOODSID = _Goods.GOODSID;
                    _UpdateGoodsModel.QTYEXE -= _Goods.QTYEXE;
                    _UpdateGoodsModel.CREATERID = _Goods.CREATERID;
                    _GoodsModel.Add(_UpdateGoodsModel);

                    Model.PFTGOODSinventoryModel.PostWarehouseShelvesModel _WarehouseShelvesModel = new PFTGOODSinventoryModel.PostWarehouseShelvesModel();
                    _WarehouseShelvesModel.GOODS_SN = _Goods.GOODSCODE;
                    _WarehouseShelvesModel.STOCK_MEMO = msg+":" + _Goods.QTYEXE;
                    _WarehouseShelvesModel.REAL_STOCK -= _Goods.QTYEXE;
                    _WarehouseShelvesModel.EXPIRY_DATE = DateTime.Now.ToString("yyyy/MM/dd");
                    _WarehouseShelvesModel.BATCH_NO = (_Goods.GOODSCODE + DateTime.Now.ToString("yyyyMMdd").Substring(3, 5) + _Goods.KEEPDAYS);
                    _WarehouseShel.Add(_WarehouseShelvesModel);

                    _PFT_GoodsinventoryHis.Add(new PFTGOODSinventoryModel.PFT_GoodsinventoryHis() { GOODSID = _Goods.GOODSID, QTY = _Goods.QTY, CREATERID = _Goods.CREATERID, NOTE = msg, NEWQTY = _Goods.QTY - _Goods.QTYEXE });
                    if (UnShelveType == "转仓下架")
                    {
                        listmiddlePFTStock.Add(new pft_middle_goodsinventory() { GOODSID = _Goods.GOODSID, STATUS = 1, CREATERID = _Goods.CREATERID, QTY = _Goods.QTYEXE });
                        LstmiddlePFTStockHis.Add(new pft_middle_goodsinventoryhis() { GOODSID = _Goods.GOODSID, OFFSHELVESID = 0, LMOFFSHELVESGOODSID = 0, CREATERID = _Goods.CREATERID, QTY = _Goods.QTYEXE, NOTE = "转仓上架" });
                    }
                }
                Update = UpdateGOODSQTY(tran, _GoodsModel);//数据库报损
                Update = Update && InsertgoodsinventoryHIS(tran, _PFT_GoodsinventoryHis);
                if (Update && UnShelveType == "转仓下架")
                {
                    Update = Update && InsertMiddlegoodsinventory(tran, listmiddlePFTStock);
                    Update = Update && InsertMiddlegoodsinventoryHIS(tran, LstmiddlePFTStockHis);
                }
                //MB.Util.TraceEx.Write("报损信息数量：" + _PFT_GoodsinventoryHis.Count.ToString());
                if (Update && UnShelveType == "摘果报损")
                {
                    MB.Util.TraceEx.Write("同步在线系统进行中。。。。。，信息数量：" + _WarehouseShel.Count.ToString());
                    string josnData = JsonConvert.SerializeObject(_WarehouseShel).ToString();
                    Update = Update && OnlineStockBll.NewInstance.setOnlineStock(josnData, "OFF", out message);
                }
                //提交事务
                if (Update)
                {
                    tran.Commit();
                }
                else
                {
                    tran.Rollback();
                }

                return Update;
            }
            catch (Exception ex)
            {

                MB.Util.TraceEx.Write(ex.Message);
                message = "报损失败！\n" + ex.Message;
                return Update;
            }
            finally {
                if (tran != null) tran.Dispose();
                if (cn != null) cn.Close();
                if (cn != null) cn.Dispose();
            }
        

        }
        /// <summary>
        /// 商品报损
        /// </summary>
        /// <param name="transaction"></param>
        /// <param name="Goodsinventory"></param>
        /// <returns></returns>
        public bool UpdateGOODSQTY(DbTransaction transaction, List<Model.PFTGOODSinventoryModel.GetGoodsModel> Goodsinventory)
        {
     
            try
            {
                using (MB.RuleBase.BulkCopy.IDbBulkExecute bulk = MB.RuleBase.BulkCopy.DbBulkExecuteFactory.CreateDbBulkExecute(transaction))
                {
                    
                    bulk.WriteToServer("Goods", "UpdateGoodsinventory", Goodsinventory);
                }

                return true;
            }
            catch (Exception ex)
            {
                MB.Util.TraceEx.Write(ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 报损日志插入
        /// </summary>
        /// <param name="transaction"></param>
        /// <param name="GoodsinventoryHis"></param>
        /// <returns></returns>
        private bool InsertgoodsinventoryHIS(DbTransaction transaction, List<PFTGOODSinventoryModel.PFT_GoodsinventoryHis> GoodsinventoryHis)
        {

            try
            {
                if (GoodsinventoryHis == null || GoodsinventoryHis.Count <= 0) return false;

                using (MB.RuleBase.BulkCopy.IDbBulkExecute bulk = MB.RuleBase.BulkCopy.DbBulkExecuteFactory.CreateDbBulkExecute(transaction))
                {
                    bulk.WriteToServer("Goods", "InsertGoodsinventoryHIS", GoodsinventoryHis);
                }

                return true;
            }
            catch (Exception ex)
            {
                MB.Util.TraceEx.Write(ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 摘果库存修改
        /// </summary>
        /// <param name="message"></param>
        /// <param name="List_UpdateGoodsinventory"></param>
        /// <returns></returns>
        public bool PFT_UpdateGoodsinventory(out string message, List<Model.PFTGOODSinventoryModel.PFT_UpdateGoodsinventory> List_UpdateGoodsinventory)
        {
            bool result = false;
            message = null;
            var oracle = new MB.RuleBase.BulkCopy.SimulatedOracleHelper();
            var db = MB.Orm.Persistence.DatabaseHelper.CreateDatabase();
            var cn = oracle.CreateOracleConnection(db.ConnectionString);
            System.Data.Common.DbTransaction tran = null;
            try
            {
                cn.Open();
                tran = cn.BeginTransaction();
                List<PFTGOODSinventoryModel.PFT_GoodsinventoryHis> _PFT_GoodsinventoryHis = new List<PFTGOODSinventoryModel.PFT_GoodsinventoryHis>();
                foreach (var _Goodsinventory in List_UpdateGoodsinventory)
                {
                    _PFT_GoodsinventoryHis.Add(new PFTGOODSinventoryModel.PFT_GoodsinventoryHis() { GOODSID = _Goodsinventory.GOODSID, QTY = _Goodsinventory.QTY, CREATERID = _Goodsinventory.CREATERID, NOTE = "摘果库存修改", NEWQTY = _Goodsinventory.NEWQTY });
                }
                MB.Util.TraceEx.Write("修改信息数量：" + _PFT_GoodsinventoryHis.Count.ToString());
                InsertgoodsinventoryHIS(tran, _PFT_GoodsinventoryHis);
                using (MB.RuleBase.BulkCopy.IDbBulkExecute bulk = MB.RuleBase.BulkCopy.DbBulkExecuteFactory.CreateDbBulkExecute(tran))
                {
                    bulk.WriteToServer("Goods", "UpdatePFTGoodsinventory", List_UpdateGoodsinventory);
                }
                result = true;
                if (result)
                {
                    tran.Commit();
                }
                else
                {
                    tran.Rollback();
                }
                return result;
            }
            catch (Exception ex)
            {
                MB.Util.TraceEx.Write(ex.Message);
                message = "修改失败！\n" + ex.Message;
                return result;
            }
            finally
            {
                if (tran != null) tran.Dispose();
                if (cn != null) cn.Close();
                if (cn != null) cn.Dispose();
            }
        }

        private bool InsertMiddlegoodsinventory(DbTransaction transaction, List<pft_middle_goodsinventory> MiddleGoodsinventory)
        {
            try
            {
                if (MiddleGoodsinventory == null || MiddleGoodsinventory.Count <= 0) return false;

                using (MB.RuleBase.BulkCopy.IDbBulkExecute bulk = MB.RuleBase.BulkCopy.DbBulkExecuteFactory.CreateDbBulkExecute(transaction))
                {
                    bulk.WriteToServer("Goods", "InsertMiddleGoodsinventory", MiddleGoodsinventory);
                }

                return true;
            }
            catch (Exception ex)
            {
                MB.Util.TraceEx.Write(ex.Message);
                return false;
            }
        }

        private bool InsertMiddlegoodsinventoryHIS(DbTransaction transaction, List<pft_middle_goodsinventoryhis> MiddleGoodsinventoryHis)
        {

            try
            {
                if (MiddleGoodsinventoryHis == null || MiddleGoodsinventoryHis.Count <= 0) return false;

                using (MB.RuleBase.BulkCopy.IDbBulkExecute bulk = MB.RuleBase.BulkCopy.DbBulkExecuteFactory.CreateDbBulkExecute(transaction))
                {
                    bulk.WriteToServer("Goods", "InsertMiddleGoodsinventoryHIS", MiddleGoodsinventoryHis);
                }

                return true;
            }
            catch (Exception ex)
            {
                MB.Util.TraceEx.Write(ex.Message);
                return false;
            }
        }

        /// <summary>
        /// 中间仓库存修改（废弃），改为上架摘果仓库存
        /// </summary>
        /// <param name="message"></param>
        /// <param name="List_UpdateGoodsinventory"></param>
        /// <returns></returns>
        public bool PFT_UpdateMiddleGoodsinventory(out string message,int UserID, List<pft_middle_inventoryTMP> List_UpdateMiddleGoodsinventory)
        {
            bool result = false;
            message = null;
            var oracle = new MB.RuleBase.BulkCopy.SimulatedOracleHelper();
            var db = MB.Orm.Persistence.DatabaseHelper.CreateDatabase();
            var cn = oracle.CreateOracleConnection(db.ConnectionString);
            System.Data.Common.DbTransaction tran = null;
            try
            {
                cn.Open();
                tran = cn.BeginTransaction();
                List<pft_middle_goodsinventoryhis> _PFT_middleGoodsinventoryHis = new List<pft_middle_goodsinventoryhis>();
                foreach (var _Goodsinventory in List_UpdateMiddleGoodsinventory)
                {
                    _PFT_middleGoodsinventoryHis.Add(new pft_middle_goodsinventoryhis() { GOODSID = _Goodsinventory.GOODSID, OFFSHELVESID = 0, LMOFFSHELVESGOODSID = 0, CREATERID = UserID, QTY = _Goodsinventory.INVQTY , NEWQTY=_Goodsinventory.QTYEXCE, NOTE = "库存调整" });
                    _Goodsinventory.CREATERID = UserID;
                }
                MB.Util.TraceEx.Write("修改信息数量：" + _PFT_middleGoodsinventoryHis.Count.ToString());
                InsertMiddlegoodsinventoryHIS(tran, _PFT_middleGoodsinventoryHis);
                using (MB.RuleBase.BulkCopy.IDbBulkExecute bulk = MB.RuleBase.BulkCopy.DbBulkExecuteFactory.CreateDbBulkExecute(tran))
                {
                    bulk.WriteToServer("Goods", "UpdatePFTMiddleGoodsinventory", List_UpdateMiddleGoodsinventory);
                }
                result = true;
                if (result)
                {
                    tran.Commit();
                }
                else
                {
                    tran.Rollback();
                }
                return result;
            }
            catch (Exception ex)
            {
                MB.Util.TraceEx.Write(ex.Message);
                message = "修改失败！\n" + ex.Message;
                return result;
            }
            finally
            {
                if (tran != null) tran.Dispose();
                if (cn != null) cn.Close();
                if (cn != null) cn.Dispose();
            }
        }

    }
}
